<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加员工</el-button>
    <el-table :data="employees" style="width: 100%">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="department" label="职位"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteEmployee(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加员工" :visible.sync="addDialogVisible">
      <el-input v-model="newEmployee.name" placeholder="员工姓名"></el-input>
      <el-input v-model="newEmployee.position" placeholder="职位"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addEmployee">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑员工" :visible.sync="editDialogVisible">
      <el-input v-model="editEmployeeData.name" placeholder="员工姓名"></el-input>
      <el-input v-model="editEmployeeData.position" placeholder="职位"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateEmployee">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      employees: [],
      addDialogVisible: false,
      editDialogVisible: false,
      newEmployee: { name: '', position: '' },
      editEmployeeData: { id: '', name: '', position: '' }
    };
  },
  created() {
    this.fetchEmployees();
  },
  methods: {
    fetchEmployees() {
      axios.get('/api/employees').then(response => {
        this.employees = response.data;
      });
    },
    openAddDialog() {
      this.addDialogVisible = true;
      this.newEmployee = { name: '', position: '' };
    },
    addEmployee() {
      axios.post('/api/employees', this.newEmployee).then(() => {
        this.fetchEmployees();
        this.addDialogVisible = false;
      });
    },
    openEditDialog(employee) {
      this.editDialogVisible = true;
      this.editEmployeeData = { ...employee };
    },
    updateEmployee() {
      axios.put(`/api/employees/${this.editEmployeeData.id}`, this.editEmployeeData).then(() => {
        this.fetchEmployees();
        this.editDialogVisible = false;
      });
    },
    deleteEmployee(id) {
      axios.delete(`/api/employees/${id}`).then(() => {
        this.fetchEmployees();
      });
    }
  }
};
</script>
